"""
@Author  : 康帅
@Time    : 2021/3/15 13:56
@Function: 单例模式实现二：自定义metaclass的方法
"""


class Singleton(type):
    """ 实现方式二 """

    def __init__(cls, name, bases=None, dict=None):
        super().__init__(name, bases, dict)
        # 初始化全局变量cls._instance = None
        cls._instance = None

    def __call__(cls, *args, **kwargs):
        # 控制对象的创建过程，如过cls._instance = None则创建，否则直接返回
        if cls._instance is None:
            cls._instance = super().__call__(*args, **kwargs)
        return cls._instance


class CustomClass(metaclass=Singleton):
    """ 自定义用户类 """

    def __init__(self, name):
        self.__name = name

    def get_name(self):
        return self.__name


if __name__ == '__main__':
    tony = CustomClass("Tony")
    jack = CustomClass("Jack")
    print(tony.get_name(), jack.get_name())
    print("id(tony):", id(tony), "id(jack)", id(jack))
    print("tony == jack:", tony == jack)
